package com.anolesoft.twelvePlan.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.anolesoft.common.core.constant.HttpStatus;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.twelvePlan.dto.MesPlanJiedianDTO;
import com.anolesoft.twelvePlan.dto.MesPlanJiedianExport;
import com.anolesoft.twelvePlan.listener.MesPlanJiedianListener;
import com.anolesoft.twelvePlan.service.MesPlanJiedianService;
import com.anolesoft.twelvePlan.vo.MesPlanJiedianVO;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.Constants;
import com.anolesoft.yr.util.PageData;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyq
 * @date 2022/8/11
 */
@RestController
@RequestMapping(value="/plan/jiedian")
@Slf4j
public class MesPlanJiedianController {
    @Autowired
    private MesPlanJiedianService mesPlanJiedianService;

    @GetMapping("/query")
    public AjaxResult queryJiedian(MesPlanJiedianVO mesPlanJiedianVO) {
        log.debug("mesPlanJiedianVO: {}", mesPlanJiedianVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesPlanJiedianDTO mesPlanJiedianDTO = BeanUtil.copyProperties(mesPlanJiedianVO,MesPlanJiedianDTO.class);
        mesPlanJiedianDTO.setFactoryId(loginUser.getFacCode());
        Integer pageSize = mesPlanJiedianVO.getPageSize();
        Integer pageNo = mesPlanJiedianVO.getPageNo();
        log.debug("mesPlanJiedianDTO:{}",mesPlanJiedianDTO);
        PageData<List<MesPlanJiedianDTO>> listPageData = this.mesPlanJiedianService.queryJiedian(mesPlanJiedianDTO,pageNo,pageSize);
        List<MesPlanJiedianVO> mesPlanJiedianVOList = listPageData.getItems().stream()
                .map(t -> BeanUtil.copyProperties(t,MesPlanJiedianVO.class))
                .collect(Collectors.toList());
        PageResult pageResult = new PageResult(mesPlanJiedianVOList, pageSize, pageNo, listPageData.getTotal());
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, pageResult);
    }

    @PostMapping("/insert")
    public AjaxResult insertJiedian(@RequestBody MesPlanJiedianVO mesPlanJiedianVO) {
        log.debug("mesPlanJiedianVO: {}", mesPlanJiedianVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesPlanJiedianDTO mesPlanJiedianDTO = BeanUtil.copyProperties(mesPlanJiedianVO,MesPlanJiedianDTO.class);
        mesPlanJiedianDTO.setFactoryId(loginUser.getFacCode());
        mesPlanJiedianDTO.setCrerateId(loginUser.getEmpUid());
        log.debug("mesPlanJiedianDTO:{}",mesPlanJiedianDTO);
        int count = this.mesPlanJiedianService.insertJiedian(mesPlanJiedianDTO);
        if (count == 1) {
            return AjaxResult.success("新增成功！");
        } else if (count == 0){
            return AjaxResult.success("该条记录已经存在！");
        } else {
            return AjaxResult.success("新增失败，请重试");
        }
    }

    @PostMapping("/update")
    public AjaxResult updateJiedian(@RequestBody MesPlanJiedianVO mesPlanJiedianVO) {
        log.debug("mesPlanJiedianVO: {}", mesPlanJiedianVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesPlanJiedianDTO mesPlanJiedianDTO = BeanUtil.copyProperties(mesPlanJiedianVO,MesPlanJiedianDTO.class);
        mesPlanJiedianDTO.setFactoryId(loginUser.getFacCode());
        mesPlanJiedianDTO.setModifyId(loginUser.getEmpUid());
        log.debug("mesPlanJiedianDTO:{}",mesPlanJiedianDTO);
        int count = this.mesPlanJiedianService.updateJiedian(mesPlanJiedianDTO);
        if (count == 1) {
            return AjaxResult.success("修改成功！");
        } else if (count == 0){
            return AjaxResult.success("该条记录已经存在！");
        } else {
            return AjaxResult.success("修改失败，请重试");
        }
    }

    @PostMapping("/delete")
    public AjaxResult deleteJiedian(@RequestBody MesPlanJiedianVO mesPlanJiedianVO) {
        log.debug("mesPlanJiedianVO: {}", mesPlanJiedianVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesPlanJiedianDTO mesPlanJiedianDTO = BeanUtil.copyProperties(mesPlanJiedianVO,MesPlanJiedianDTO.class);
        //mesPlanJiedianDTO.setFactoryId(loginUser.getFacCode());
        mesPlanJiedianDTO.setDeleteId(loginUser.getEmpUid());
        log.debug("mesPlanJiedianDTO:{}",mesPlanJiedianDTO);
        int count = this.mesPlanJiedianService.deleteJiedian(mesPlanJiedianDTO);
        if (count == 1) {
            return AjaxResult.success("删除成功！");
        } else {
            return AjaxResult.success("删除失败，请重试");
        }
    }
    @PostMapping(value = "/export")
    public void exportJiedian(@RequestBody MesPlanJiedianVO mesPlanJiedianVO, HttpServletResponse response){
        long start = System.currentTimeMillis();
        log.debug("mesPlanJiedianVO: {}", mesPlanJiedianVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesPlanJiedianDTO mesPlanJiedianDTO = BeanUtil.copyProperties(mesPlanJiedianVO, MesPlanJiedianDTO.class);
        mesPlanJiedianDTO.setFactoryId(loginUser.getFacCode());
        log.debug("mesPlanJiedianDTO: {}", mesPlanJiedianDTO);
        try {
            OutputStream output = response.getOutputStream();
            //字符集
            response.setCharacterEncoding("utf-8");
            //类型
            response.setContentType("multipart/form-data");
            //响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(("export.xlsx").getBytes("gb2312"),"ISO8859-1"));
            //总条数
            int total = this.mesPlanJiedianService.exportJiedian(mesPlanJiedianDTO);
            log.debug("total:" + total);
            //单个sheet最大条数
            int size = 100000;
            //sheet数
            int sheet = total / size + 1;
            //单次查询条数
            int pageSize = 1000;
            ExcelWriter excelWriter = EasyExcel.write(output).build();
            //执行查询次数
            int count = 1;
            for (int i = 0; i < sheet ; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i,"节点周期表" + (i+1))
                        .head(MesPlanJiedianExport.class)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .build();
                int rolling;
                if (i == sheet - 1) {
                    rolling = (total - i * size) / pageSize + 1;
                } else {
                    rolling = size / pageSize;
                }
                for (int j = 0; j < rolling; j++) {
                    PageData<List<MesPlanJiedianDTO>> listPageData = this.mesPlanJiedianService.queryJiedian(mesPlanJiedianDTO, count,pageSize);
                    List<MesPlanJiedianExport> datas = listPageData.getItems().stream().map(item -> {
                        MesPlanJiedianExport mesPlanJiedianExport = new MesPlanJiedianExport();
                        BeanUtil.copyProperties(item, mesPlanJiedianExport);
                        return mesPlanJiedianExport;
                    }).collect(Collectors.toList());
                    excelWriter.write(datas, writeSheet);
                    count++;
                }
            }
            log.debug("查询次数：" + (count - 1) + "次");
            //刷新流
            excelWriter.finish();
            output.flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("导出失败：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            long end = System.currentTimeMillis();
            log.debug("总用时：" + (end - start) + "毫秒");
        }
    }

    @PostMapping(value="/import")
    public AjaxResult importEqual(MultipartFile file){
        log.debug("文件名：{}", file.getOriginalFilename());
        log.debug("文件大小：{}", file.getSize());

        try {
            EasyExcel.read(file.getInputStream(), MesPlanJiedianExport.class, new MesPlanJiedianListener(mesPlanJiedianService)).sheet(0).doRead();
            return AjaxResult.success("文件导入成功！");
        } catch (IOException e) {
            log.error("导入失败：{}", e.getMessage());
            e.printStackTrace();
            return AjaxResult.success("文件导入异常" + e.getMessage());
        }
    }

}
